package com.tmt.im.manager.helper;

import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import java.security.Principal;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/23 11:03
 * @Version 1.0
 **/
public class PrincipalHelper {

    /**
     * 获取当前用户的ID
     *
     * @param principal
     * @return
     */
    public static Long getCurrentUserId(Principal principal) {
        if (principal instanceof BearerTokenAuthentication token) {
            //查询当前用户的ID。
            return (Long) token.getTokenAttributes().get("id");
        }else if (principal instanceof OAuth2AuthenticationToken token){
            return token.getPrincipal().getAttribute("id");
        }else if (principal instanceof JwtAuthenticationToken token){
            return token.getToken().getClaim("id");
        }
        return null;
    }
}
